'''
Author: admin@attacker.club
Date: 2022-11-02 16:23:08
LastEditTime: 2023-03-15 19:14:16
Description: 
'''
# -*- coding: utf-8 -*-
# __author__ = 'sky'

from awsops import AwsOps

class AwsIns():
    def __init__(self, account, region='us-west-1'):
        aws = AwsOps()
        aws.account = account
        aws.service_name = 'ec2'
        aws.region = region
        self.cli = aws.get_client()

    def getEip(self, instanceid):
        """获取ssr机器的现行的ip"""
        response = self.cli.describe_instances(InstanceIds=instanceid)
        for reservation in response["Reservations"]:
            for instance in reservation["Instances"]:
                if "PublicIpAddress" in instance:
                # if instance.has_key("PublicIpAddress") is True:
                    eip = instance["PublicIpAddress"]
                    return eip
                else:
                    return None

    def getvpcIP(self):
        """获取一个vpc的ip地址"""
        response = self.cli.allocate_address(Domain='vpc')
        return response

    def relasevpcIP(self, allocationid):
        """回收一个vpc的ip地址,参数必须为id"""
        response = self.cli.release_address(AllocationId=allocationid)
        return response

    def assovpcIP(self, allocationid, instanceid):
        """挂载ip到ec2上"""
        response = self.cli.associate_address(InstanceId=instanceid[0], AllocationId=allocationid)
        return response

    def diassvpncIP(self, assid):
        """取消IP的挂载"""
        response = self.cli.disassociate_address(AssociationId=assid)
        return response

    def getAid(self, publicip):
        response = self.cli.describe_addresses(PublicIps=publicip)
        if response:
            for i in response["Addresses"]:
                allid, assid = i["AllocationId"],i["AssociationId"]
                return allid, assid
        else:
            raise Exception("allid、assid获取失败")
